//
//  iGSSAppDelegate.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "iGSSAppDelegate.h"
#import "HomeViewController.h"
#import "GSSCommunicator.h"
#import "NSData+Base64.h"

@implementation iGSSAppDelegate

@synthesize window;

- (void)dealloc {
    [homeViewController release];
	[navigationController release];
	[window release];
	[super dealloc];
}


//MARK: -

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    NSArray *args = [[url query] componentsSeparatedByString:@"&"];
    GSSCommunicator *communicator = [GSSCommunicator defaultCommunicator];
    
    for (NSString *arg in args) {
        if ([arg length] < 3)
            continue;
        NSString *key = [arg substringToIndex:2];
        NSString *val = [arg substringFromIndex:2];
        
        if ([key isEqualToString:@"u="])
			communicator.username = [val stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		else if ([key isEqualToString:@"t="])
			communicator.token = [NSData dataFromBase64String:val];
    }
    
    [homeViewController reload];
    [homeViewController refreshPressed];
    
	return YES;
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    homeViewController = [[HomeViewController alloc] init];
    navigationController = [[UINavigationController alloc]
                            initWithRootViewController:homeViewController];
	[window addSubview:navigationController.view];
    [window makeKeyAndVisible];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	[[NSUserDefaults standardUserDefaults] synchronize];
}

@end
